package com.android.boncen.commonFrame.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.boncen.commonFrame.MyApplication;
import com.android.boncen.commonFrame.R;
import com.android.boncen.commonFrame.activity.PressureActivity;
import com.android.boncen.commonFrame.bean.GlucoseHistoryBean;
import com.android.boncen.commonFrame.bean.UserBean;
import com.android.boncen.commonFrame.user.UserInfoActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 记录
 */
public class RecordFragment extends Fragment {


    @BindView(R.id.tv_bf_before)
    TextView tvBfBefore;
    @BindView(R.id.tv_lunch_before)
    TextView tvLunchBefore;
    @BindView(R.id.tv_dinner_before)
    TextView tvDinnerBefore;
    @BindView(R.id.tv_dinner_after)
    TextView tvDinnerAfter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.record_fragment, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getToday();
    }


    @OnClick({R.id.user, R.id.add, R.id.clock_time, R.id.ib_bloodpressure, R.id.ib_bmi, R.id.ib_bloodhgb})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ib_bloodpressure:
                PressureActivity.start(getContext(),1);
                break;
            case R.id.ib_bmi:
                PressureActivity.start(getContext(),3);
                break;
            case R.id.ib_bloodhgb:
                PressureActivity.start(getContext(),2);
                break;
            case R.id.clock_time:
                if (MyApplication.isAlarm(getContext())) {
                    new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("是否重新设置或者取消提醒").setNeutralButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //取消定时
                            MyApplication.save(getContext(), false);
                            MyApplication.cancelAlarm(getContext());
                            Toast.makeText(getContext(), "取消定时成功", Toast.LENGTH_SHORT).show();
                        }
                    }).create().show();

                } else {
                    Toast.makeText(getContext(), "开启定时提醒", Toast.LENGTH_SHORT).show();
                    //启动定时
                    MyApplication.save(getContext(), true);
                    MyApplication.setAlarm(getContext());
                }
                break;
            case R.id.user:
                Intent intent = new Intent(getContext(), UserInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.add:
                new AddGlucoseDialog(getActivity(), new AddGlucoseDialog.SaveCallback() {
                    @Override
                    public void save(int type, float size) {
                        if (isAddGlucoseHistory( type))
                        {
                            Toast.makeText(getContext(), "当前类型今天已经添加1次", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        addGlucoseHistoryBean(type, size);
                    }
                }).show();
                break;
        }
    }

    // 每天每个类型1次
    private boolean isAddGlucoseHistory(int type)
    {
        for (GlucoseHistoryBean bean:list)
        {
            if (bean.getType() == type)
            {
                return true;
            }
        }
        return  false;
    }
    //保存血糖记录
    private void addGlucoseHistoryBean(int type, float bloodSugar) {
        UserBean user = BmobUser.getCurrentUser(UserBean.class);
        GlucoseHistoryBean gameScore = new GlucoseHistoryBean();
        gameScore.setUserId(user.getObjectId());
        gameScore.setTypeBlood(0);
        gameScore.setType(type);
        gameScore.setBloodSugar(bloodSugar);

        gameScore.save(new SaveListener<String>() {

            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Toast.makeText(getContext(), "保存数据成功", Toast.LENGTH_SHORT).show();
                    getToday();
                } else {
                    Toast.makeText(getContext(), "保存数据失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /***
     * 今天记录
     */
    private void getToday() {
        BmobQuery<GlucoseHistoryBean> query = new BmobQuery<GlucoseHistoryBean>();
        List<BmobQuery<GlucoseHistoryBean>> and = new ArrayList<BmobQuery<GlucoseHistoryBean>>();
        //大于00：00：00
        BmobQuery<GlucoseHistoryBean> q1 = new BmobQuery<GlucoseHistoryBean>();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        q1.addWhereGreaterThanOrEqualTo("createdAt", new BmobDate(calendar.getTime()));
        and.add(q1);
        //小于23：59：59

        BmobQuery<GlucoseHistoryBean> q2 = new BmobQuery<GlucoseHistoryBean>();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        q2.addWhereLessThanOrEqualTo("createdAt", new BmobDate(calendar.getTime()));
        and.add(q2);

        //添加复合与查询
        query.and(and);

        UserBean user = BmobUser.getCurrentUser(UserBean.class);

        query.addWhereEqualTo("userId", user.getObjectId());
        query.addWhereEqualTo("typeBlood", 0);
        query.findObjects(new FindListener<GlucoseHistoryBean>() {
            @Override
            public void done(List<GlucoseHistoryBean> list, BmobException e) {
                if (list == null || list.isEmpty()) {
                    return;
                }
                setDataView(list);
            }
        });
    }
    List<GlucoseHistoryBean> list = new ArrayList<>();
    private void setDataView(List<GlucoseHistoryBean> list) {
        this.list.clear();
        this.list.addAll(list);

        Collections.sort(list, new CameraSizeComparator());
        //早餐 前-后
        StringBuilder breakfest = new StringBuilder();
        //午餐 前-后
        StringBuilder lunch = new StringBuilder();
        //晚餐 前-后
        StringBuilder dinner = new StringBuilder();
        //睡前 前-后
        StringBuilder beforesleep = new StringBuilder();

        for (GlucoseHistoryBean bean : list) {
            switch (bean.getType()) {
                case 0:
                    breakfest.append(getTextColorSelect(bean.getBloodSugar())).append("/");
                    break;
                case 1:
                    breakfest.append(getTextColorSelect(bean.getBloodSugar()));
                    break;
                case 2:
                    lunch.append(getTextColorSelect(bean.getBloodSugar())).append("/");
                    break;
                case 3:
                    lunch.append(getTextColorSelect(bean.getBloodSugar()));
                    break;
                case 4:
                    dinner.append(getTextColorSelect(bean.getBloodSugar())).append("/");
                    break;
                case 5:
                    dinner.append(getTextColorSelect(bean.getBloodSugar()));
                    break;
                case 6:
                    beforesleep.append(getTextColorSelect(bean.getBloodSugar())).append("/");
                    break;
            }
        }

        tvBfBefore.setText(Html.fromHtml(breakfest.toString()));
        tvLunchBefore.setText(Html.fromHtml(lunch.toString()));
        tvDinnerBefore.setText(Html.fromHtml(dinner.toString()));
        tvDinnerAfter.setText(Html.fromHtml(beforesleep.toString()));
    }

    private String getTextColorSelect(float bloodNum) {


        if (bloodNum > 10.0) {

            return "<font color=\"#FF3030\">" + bloodNum + "</font>";
        } else if (bloodNum < 4.0) {

            return "<font color=\"#EEAD0E\">" + bloodNum + "</font>";
        } else {

            return "<font color=\"#228B22\">" + bloodNum + "</font>";
        }

    }

    private static class CameraSizeComparator implements Comparator<GlucoseHistoryBean> {
        public int compare(GlucoseHistoryBean lhs, GlucoseHistoryBean rhs) {
            if (lhs.getType() == rhs.getType()) {
                return 0;
            } else if (lhs.getType() > rhs.getType()) {
                return 1;
            } else {
                return -1;
            }
        }

    }


}
